<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/5/28
 * Time: 12:00
 */

namespace App\HttpController;

use App\Model\FileModel;
use App\Services\QiniuService;
use EasySwoole\EasySwoole\Config;
use EasySwoole\Http\Message\Status;
use EasySwoole\Validate\Validate;
/**文件管理
 * Class File
 * @package App\HttpController
 */
class File extends ApiController
{
    /**
     * showdoc
     * @catalog 公共接口/文件上传
     * @title 文件上传
     * @description 文件上传
     * @method POST
     * @url /File
     * @param file 是 file 文件,请直接放表单，无需放在加密文件，为了不影响你业务，你加密可以搞个空数据
     * @param  type 是 文件业务类型，1私聊2群聊3头像4相册，后续有其他的在联系增加
     * @return {"code":200,"result":'WOut2yeSh2TFgRrrDCmgXw==',"msg":"上传成功"}
     * @return_param  code int 状态码(200:成功0:失败401:未登录)
     * @return_param  data string 返回结果
     * @return_param  msg string 返回提示语
     * @return_param  id int 文件id
     * @return_param  filename string 文件名
     * @return_param  path string 文件路径
     * @return_param size int 文件大小
     * @return_param id int 文件id
     * @return_param type int 业务类型
     * @remark 上传的文件，如果没有保存之类的，系统会在一天后自动删除
     */
    function Upload(){
        $file = $this->request()->getUploadedFile('file');
        if($file->getError()){
            return $this->writeJson(Status::CODE_BAD_REQUEST, '', '文件上传错误');
        }

        $param = $this->param;
        $param['type'] = '1';
        $valitor = new Validate();
        $valitor->addColumn('type', '业务类型')->required('业务类型不为空')->numeric()->between(0,10);
        $bool = $valitor->validate($param);
        if(!$bool){
            return $this->writeJson(Status::CODE_BAD_REQUEST, '', $valitor->getError()->__toString());
        }

        //文本、图片、视频，其他类文件用白名单机制
        $white = array(
            'application/msword',#doc文件
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',#docx
            'application/pdf',#pdf
            'application/vnd.ms-excel',#xls
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',#xlsx
            'application/vnd.ms-powerpoint',#ppt
            'application/vnd.openxmlformats-officedocument.presentationml.presentation',#pptx
            'application/x-zip-compressed',#zip
            'application/octet-stream',#rar
            'application/x-shockwave-flash',#swf
        );

        $pos = strpos($file->getClientMediaType(),'/');
        $type = substr($file->getClientMediaType(),0,$pos);

         switch ($type){
             case 'video';
             case 'text':
             case 'image':
                 break;
             case 'application':
                if(!in_array($file->getClientMediaType(),$white)){
                    return $this->writeJson(Status::CODE_UNSUPPORTED_MEDIA_TYPE, '', '不允许这类文件上传');
                }
                break;
             default:
                 return $this->writeJson(Status::CODE_UNSUPPORTED_MEDIA_TYPE, '', '不允许这类文件上传');
         }

         $dir = $this->getdir();

         $path = $dir.time().$file->getClientFilename();
        //移动文件
        if(!$file->moveto( $path)){
            return $this->writeJson(Status::CODE_BAD_REQUEST,'', "上传保存文件失败");
        }

        //保存文件
       $data = array(
            'size'=> $file->getSize(),
            'mine'=>$file->getClientMediaType(),
            'path'=> $path,
            'type'=> $param['type'],
            'filename'=>$file->getClientFilename(),
        );
        $fileModel = new FileModel();
       $ret =   $fileModel->data($data)->save();
        if($ret){
            $data['id'] = $ret;
          return   $this->writeJson(Status::CODE_OK,  $data, "上传成功");
        }
        return   $this->writeJson(Status::CODE_BAD_REQUEST,'', "保存失败");
    }

    private function  getdir(){
        $baseFoloder = Config::getInstance()->getConf('UPLOAD_FOLDER');
        if(!is_dir("./".  $baseFoloder)){
            mkdir($baseFoloder);
        }
        $year = date("Y");
        if(!is_dir('./'.$baseFoloder.'/'.$year)){
            mkdir('./'.$baseFoloder.'/'.$year);
        }
        $month = date("m");
        if(!is_dir('./'.$baseFoloder.'/'.$year.'/'.$month)){
            mkdir('./'.$baseFoloder.'/'.$year.'/'.$month);
        }
        $day = date("d");
        if(!is_dir('./'.$baseFoloder.'/'.$year.'/'.$month.'/'.$day)){
            mkdir('./'.$baseFoloder.'/'.$year.'/'.$month.'/'.$day);
        }
        return  './'.$baseFoloder.'/'.$year.'/'.$month.'/'.$day.'/';
    }

    /**
     * showdoc
     * @catalog 公共接口/获取七牛token
     * @title 获取七牛token
     * @description 获取七牛token
     * @method GET
     * @url /File/QiniuToken
     * @return {"code":200,"result":'WOut2yeSh2TFgRrrDCmgXw==',"msg":"获取成功"}
     * @return_param  code int 状态码(200:成功0:失败401:未登录)
     * @return_param  data string 返回结果
     * @return_param  msg string 返回提示语
     * @return_param  token string 七牛文件上传token
     * @return_param  domain string 文件url
     * @return_param folder string 文件夹
     * @remark
     */
    public function GetQiniuToken(){
        $userInfo = $this->userInfo;
        #$callbackBody = "hash=$(etag)&uid=$(x:uid)&name=$(fname)&size=$(fsize)&bucket=$(bucket)&mime=$(mimeType)";
        $callbackBody = "hash=$(etag)&user_id={$userInfo['id']}&app_id={$userInfo['app_id']}&name=$(fname)&size=$(fsize)&bucket=$(bucket)&mime=$(mimeType)";
        $policy = [
            "callbackUrl" =>  "http://106.52.140.176:9501/Qiniucallback",
            "callbackBody" => $callbackBody,
            "fsizeLimit" => 150 * 1024 * 1024,
          //  "mimeLimit" => "audio/midi;audio/acc;audio/mpeg;audio/ogg;image/jpeg;image/png;image/jpg;image/gif;application/octet-stream;application/vnd.ms-excel;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;application/vnd.openxmlformats-officedocument.wordprocessingml.document;application/msword;video/mp4;video/avi;video/x-flv;video/mpeg;video/x-ms-wmv;video/quicktime;application/x-7z-compressed;application/zip;text/csv;text/plain;"
        ];

        $auth = new \EasySwoole\Oss\QiNiu\Auth(Config::getInstance()->getConf('QINIU.QINIU_ACCESS_KEY'),Config::getInstance()->getConf('QINIU.QINIU_SECRET_KEY'));
        $token = $auth->uploadToken('wangtuizhijia', null, 3600, $policy);
        $reponse['token']=$token;
        $reponse['domain'] = 'cdn.wangtuizhijia.com';
        $reponse['folder'] = $this->userInfo['app_id'] ;
        return   $this->writeJson(Status::CODE_OK, $reponse , "token成功");
    }


    /**
     * 上传回调
     */
    public function Qiniucallback(){
        $params = $this->request()->getRequestParam();
        $service = new QiniuService();
        $res = $service->qiniuCallBack($params, $this->request()->getHeader("authorization"));
       if($res==false){
           $resp = array('ret' => 'failed');
       }else{
           $resp = array('ret' => 'success');
       }
        $this->response()->write(json_encode(   $resp, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
        $this->response()->withStatus(200);
        return true;
    }
}